package com.xuxueli.commontdemo.util;
import com.mysql.cj.jdbc.result.ResultSetMetaData;
import com.mysql.cj.result.Field;
import com.xuxueli.commontdemo.entity.ApiResponseParam;
import com.xuxueli.commontdemo.entity.OpenApiResponseBO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 执行总数
 */
@Component
public class ToolUtils {

    /**
     * 获取查询总条数
     */
    public int getTotal(Connection conn, String totalSql) throws SQLException {
        int total = 0;
        ResultSet totalResult = conn.prepareStatement("select count(1) from (" + totalSql + ") as xx").executeQuery();
        if (totalResult.next()) {
            total = totalResult.getInt(1);
        }
        return total;
    }

    public List<OpenApiResponseBO> getResponseData(ResultSet resultSet) throws SQLException {

        List<OpenApiResponseBO> openApiResponseDataList = new ArrayList<>();

        // 查询出来的字段信息
        ResultSetMetaData resultSetMetaData = (ResultSetMetaData) resultSet.getMetaData();
        Field[] fields = resultSetMetaData.getFields();
        while (resultSet.next()) {
            OpenApiResponseBO responseItem = new OpenApiResponseBO();
            for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
                int columnType = resultSetMetaData.getColumnType(i);
                if (JdbcTypeUtils.isLob(columnType)){
                    continue;
                }
                String columnName = resultSetMetaData.getColumnName(i).trim();
               /* String columnName = null;
                for (Field field : fields) {
//                    if (field.getOriginalName().equals(name)) {
                        columnName = field.getName();
//                    }
                }*/
                if (null == resultSet.getObject(i)) {
                    responseItem.set(columnName, "");
                } else {
                    if (JdbcTypeUtils.isDate(columnType)) {
                        responseItem.set(columnName, resultSet.getObject(i).toString());
                    } else {
                        responseItem.set(columnName, resultSet.getObject(i));
                    }
                }
            }
            openApiResponseDataList.add(responseItem);
        }
        return openApiResponseDataList;
    }

    /**
     * 返回值映射MAP
     */
    public Map<String, ApiResponseParam> responseColumnMappingMap(List<ApiResponseParam> params) {
        Map<String, ApiResponseParam> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(params) && params.get(0).getParamName() != null) {
            params.forEach(i -> {
                if (StringUtils.isNotEmpty(i.getParamName())) {
                    map.put(i.getParamName(), i);
                }
            });
            return map;
        } else {
            return map;
        }
    }

    /**
     * 返回值映射LIST
     */
    public List<String> responseColumnMappingList(List<ApiResponseParam> params) {
        if (params.size() > 0 && params.get(0).getParamName() != null) {
            if (CollectionUtils.isEmpty(params)) {
                return new ArrayList<>();
            } else {
                List list = new ArrayList();
                params.forEach(i -> {
                    list.add(i.getColumnName());
                });
                return list;
            }
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 类型转换赋值
     */
    public static Object convertValue(Object value, int jdbcType, String clazz) {
        if (null == value) {
            return "";
        }
        if (StringUtils.isBlank(clazz)) {
            clazz = value.getClass().getName().split("\\.")[2];
        }
        String upperCase = clazz.toUpperCase();
        String v = String.valueOf(value);
        if (JdbcTypeUtils.isDate(jdbcType) && StringUtils.isNotBlank(v)) {
            try {
                java.sql.Date sqlDate = (java.sql.Date) value;
                return DateUtils.formatByMill(sqlDate.getTime(), "yyyy-MM-dd HH:mm:ss");
            } catch (Exception e) {
                // 异常情况返回原始值
                return value.toString();
            }
        }
        if (upperCase.equals("STRING")) {
            return StringUtils.isNotBlank(v) ? v : "";
        }
        if (upperCase.equals("INTEGER") || upperCase.equals("INT")) {
            return StringUtils.isNotBlank(v) ? Integer.valueOf(v) : 0;
        }
        if (upperCase.equals("LONG")) {
            return StringUtils.isNotBlank(v) ? Long.valueOf(v) : 0l;
        }
        if (upperCase.equals("DOUBLE")) {
            return StringUtils.isNotBlank(v) ? Double.valueOf(v) : 0d;
        }
        if (upperCase.equals("FLOAT")) {
            return StringUtils.isNotBlank(v) ? Float.valueOf(v) : 0f;
        }
        if (upperCase.equals("BOOLEAN")) {
            return StringUtils.isNotBlank(v) ? Boolean.valueOf(v) : false;
        }
        if (upperCase.equals("BIGDECIMAL") || upperCase.equals("DECIMAL")) {
            return StringUtils.isNotBlank(v) ? new BigDecimal(v) : new BigDecimal("0");
        }
        return value;
    }

}
